﻿using System;
using System.CodeDom;
using System.Web.Compilation;

namespace ServBus.ListForm2013.Resources
{
    internal class REFields
    {
        private string m_classKey;
        private string m_resourceKey;
        public string ClassKey
        {
            get { return m_classKey; }
        }
        public string ResourceKey
        {
            get { return m_resourceKey; }
        }
        public REFields(string classKey, string resourceKey)
        {
            m_classKey = classKey;
            m_resourceKey = resourceKey;
        }
    }

    public class ResourceExpressionBuilder : ExpressionBuilder
    {
        public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            REFields fields = parsedData as REFields;
            return new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression(typeof(ResourceExpressionBuilder)),
                "GetGlobalResourceObject",
                new CodePrimitiveExpression(fields.ClassKey),
                new CodePrimitiveExpression(fields.ResourceKey));
        }

        public override object EvaluateExpression(object target, System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            REFields fields = parsedData as REFields;
            return GetGlobalResourceObject(fields.ClassKey, fields.ResourceKey);
        }

        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            if (string.IsNullOrEmpty(expression))
            {
                throw new ArgumentException(expression + " is empty.");
            }
            REFields fields = null;
            string classKey = null;
            string resourceKey = null;
            string[] strArray = expression.Split(new char[] { ',' });
            if (strArray.Length != 2)
            {
                throw new ArgumentException(expression + " != 2");
            }
            classKey = strArray[0].Trim();
            resourceKey = strArray[1].Trim();
            fields = new REFields(classKey, resourceKey);
            return fields;
        }

        public override bool SupportsEvaluate
        {
            get
            {
                return true;
            }
        }

        public static object GetGlobalResourceObject(string classKey, string resourceKey)
        {
            DllResource res = new DllResource(classKey);
            return res.GetString(resourceKey);
        }
    }
}
